<script lang="ts" setup>
import { nextTick, ref, unref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import JsonEditor from 'jsoneditor'
import '@/assets/jsoneditor.css'
import { Close, Edit, RefreshLeft } from '@element-plus/icons-vue'
import { formatValues } from '@/utils/custom'
import { setFormDefaultParams } from '@/views/components/form/libs'

interface Props {
  params?: any
}

const props = defineProps<Props>()
const emit = defineEmits(['change'])

let editor: any = null
const editorRef = ref()
const dialogVisible = ref(false)

/**
 * 生成json编辑器
 */
const onEditorJson = (data: object) => {
  const options = {
    history: false,
    sortObjectKeys: false,
    mode: 'code',
    modes: ['code', 'text']
  }
  if (!editor) editor = new JsonEditor(unref(editorRef), options)
  editor.set(data)
}

const open = (parse?: TypedAny) => {
  dialogVisible.value = true
  nextTick(() => {
    onEditorJson(parse || props.params?.default_value_parse || {})
  })
}

/**
 * 格式化默认参数
 */
const setDefaultValue = () => {
  if (props.params) {
    const default_value_parse = props.params.default_value_parse
    const keys = Object.keys(default_value_parse)
    const items: any[] = props.params.items || props.params.columns || []
    const result = setFormDefaultParams(
      items.filter((f) => !keys.includes(f.field)),
      default_value_parse,
      true
    )
    onEditorJson(result)
  }
}

const onConfirmJson = () => {
  let data = {}
  try {
    data = editor.get()
    dialogVisible.value = false
  } catch (e) {
    ElMessage.warning('格式错误。')
  }
  emit('change', data)
}

watch(
  () => dialogVisible.value,
  (value) => {
    if (!value && editor) {
      editor.destroy()
      editor = null
    }
  }
)

defineExpose({ open })
</script>
<template>
  <el-dialog v-model="dialogVisible" title="编辑默认参数" width="70%" class="editor-dialog">
    <div class="flex align-center flex-warp pa10">
      <div v-for="(item, index) in formatValues" :key="index" class="mr10">
        <span>{{ item.label }}: </span>
        <el-tag>{{ item.value }}</el-tag>
      </div>
      <el-button
        v-if="params"
        @click="setDefaultValue"
        type="warning"
        :icon="RefreshLeft"
        class="ml-auto"
      >
        生成默认参数
      </el-button>
    </div>
    <!--json编辑器-->
    <div ref="editorRef" style="height: 500px" />
    <template #footer>
      <div class="dialog-footer">
        <el-button :icon="Close" @click="dialogVisible = false">取消</el-button>
        <el-button :icon="Edit" type="primary" @click="onConfirmJson">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss">
.editor-dialog {
  .el-overlay .el-overlay-dialog .el-dialog__body {
    padding: 0 !important;
  }
}
</style>
